package coml.jiyun.hp.frame;

import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mImg;
    /**
     * 开始
     */
    private Button mBtnStart;
    /**
     * 停止
     */
    private Button mBtnStop;
    private AnimationDrawable drawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mImg = (ImageView) findViewById(R.id.img);
        mBtnStart = (Button) findViewById(R.id.btn_start);
        mBtnStart.setOnClickListener(this);
        mBtnStop = (Button) findViewById(R.id.btn_stop);
        mBtnStop.setOnClickListener(this);

        //通过帧动画的资源文件获取AnimationDrawable示例
        drawable = (AnimationDrawable) getResources().getDrawable(R.drawable.frame_animation);
        mImg.setBackgroundDrawable(drawable);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_start:
                start();
                break;
            case R.id.btn_stop:
                stop();
                break;
        }
    }

    private void stop() {
        if (drawable != null && drawable.isRunning()){
            drawable.stop();
        }
    }

    private void start() {
        if (drawable != null && !drawable.isRunning()){
            drawable.start();
        }
    }
}
